package ini

import (
	"errors"
	"fmt"
)

type File struct {
	sections map[string]*Section
}

func newFile() *File {
	sli := make(map[string]*Section)
	sli[""] = newSection("")
	return &File {
		sections: sli,
	}
}

func (f *File) NewSection(name string) (*Section, error) {
	if len(name) == 0 {
		return nil, errors.New("节名不能为空")
	}
	if _, ok := f.sections[name]; ok {
		return nil, fmt.Errorf("节名%s已存在", name)
	}
	sec := newSection(name)
	f.sections[name] = sec
	return sec, nil
}

func (f *File) GetSection(name string) (*Section, error) {
	sec := f.sections[name]
	if sec == nil {
		return nil, fmt.Errorf("节名%s不存在", name)
	}
	return sec, nil
}

func (f *File) Section(name string) (*Section) {
	sec, err := f.GetSection(name)
	if err != nil {
		sec, _ = f.NewSection(name)
	}
	return sec
}

func (f *File) Sections() []*Section {
	sections := make([]*Section, len(f.sections))
	i := 0
	for _, v := range f.sections {
		sections[i] = v
		i++
	}
	return sections
}
